from aip import AipSpeech,AipNlp
import time,os

#生成验证码
def verifycode(session):
    #引入绘图的模块
    from PIL import Image,ImageDraw,ImageFont
    #引入随机函数
    import random
    #定义变量，用于画面的背景色，宽，高
    bgcolor = (random.randrange(20,100),random.randrange(20,100),255)
    width = 100
    height = 25
    #创建画面对象
    im = Image.new('RGB',(width,height),bgcolor)
    #创建画笔对象
    draw = ImageDraw.Draw(im)
    #调用画笔的Point()函数绘噪点
    for i in range(0,100):
        xy = (random.randrange(0,width),random.randrange(0,height))
        fill = (random.randrange(0,255),255,random.randrange(0,255))
        draw.point(xy,fill=fill)
    #定义验证码备选值
    str1="ABCDEFGHIJKLMNOPQRSTUVWXVZabcdefghijklmnopqrstuvwxvz0123456789"
    #随机选取4个值作为验证码
    rand_str = ''
    for i in range(0,4):
        rand_str += str1[random.randrange(0,len(str1))]
        
    #构造字体对象
    font = ImageFont.truetype('static/fonts/david.ttf',23)
    #构造字体颜色
    fontcolor = (255,random.randrange(0,255),random.randrange(0,255))
    #绘制4个字
    draw.text((5,0),rand_str[0],font=font,fill=fontcolor)
    draw.text((25,0),rand_str[1],font=font,fill=fontcolor)
    draw.text((50,0),rand_str[2],font=font,fill=fontcolor)
    draw.text((75,0),rand_str[3],font=font,fill=fontcolor)
    #释放画笔
    del draw
    #存入session用于进一步的验证
    session['verifycode'] = rand_str
    import io
    #print(im)
    buf = io.BytesIO()
    #将图片保存在内存中
    im.save(buf,'png')
    #print(buf)
    return buf

""" 你的 APPID AK SK """
# APP_ID = '32533647'
# API_KEY = 'C0sALM8nb5cFmZbUpZUB8W7s'
# SECRET_KEY = 'dmaqlTVhpfRccrpdUtfIcN0LlMXrEw9n'
#老师的
# APP_ID = '15420336'
# API_KEY = 'VwSGcqqwsCl282LGKnFwHDIA'
# SECRET_KEY = 'h4oL6Y9yRuvmD0oSdQGQZchNcix4TF5P'
#同学 羽泉的 
# APP_ID = '32535049'
# API_KEY = 'Xmr99m7bU8mhisQn1epKdDF6'
# SECRET_KEY = 'sarzWeaKLqFlxlGtOPfSTy2psQ3hHDXl'
APP_ID = '43514449'
API_KEY = '0FOeGW9oqeXQSyheymDNlyYd'
SECRET_KEY = 'uBM72w2ZFek2WP80lbmDzEy3ay002rdP'
client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)


  

# 读取文件
def get_file_content(filePath):
    os.system(f"ffmpeg -y  -i {filePath} -acodec pcm_s16le -f s16le -ac 1 -ar 16000 {filePath}.pcm")
    with open(f"{filePath}.pcm", 'rb') as fp:
        return fp.read()

def audio2text(filepath):
    #识别本地文件
    res = client.asr(get_file_content(filepath), 'pcm', 16000, {
        #老师的
        # 'dev_pid': 1536,
        #我的
        'dev_pid': 1536,
    })
    
    try:
        print(res)
        print(res.get("result")[0])
        return res.get("result")[0]
    except BaseException as e:
        return ""
    
#关于本地语音部分的识别